package P073_UseComparatorToSort;

import org.apache.commons.lang3.builder.CompareToBuilder;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @ClassName : UseComparatorToSort
 * @Description : 使用Comparator进行排序 Comparable接口可以实现类的默认排序法，Comparator接口则是一个类的扩展类工具
 * @Author : wukj1
 * @Date: 2022/4/1
 **/
public class UseComparatorToSort {

    @Test
    public void test(){
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"张三",Position.Boss));
        employees.add(new Employee(1006,"赵七",Position.Manager));
        employees.add(new Employee(1003,"王五",Position.Manager));
        employees.add(new Employee(1002,"李四",Position.Staff));
        employees.add(new Employee(1005,"马六",Position.Staff));
        //按员工号排序
//        Collections.sort(employees);
//        System.out.println("按员工号排序:");
//        employees.forEach(System.out::println);
        //按职位排序
//        Collections.sort(employees,new PositionComparator());
//        System.out.println("按职位排序:");
//        employees.forEach(System.out::println);
        //按职位倒序
//        Collections.sort(employees,Collections.reverseOrder(new PositionComparator()));
//        System.out.println("按职位倒序:");
//        employees.forEach(System.out::println);
        //先按职位排序，再按员工号
        Collections.sort(employees);
        System.out.println("先按职位排序，再按员工号:");
        employees.forEach(System.out::println);
    }


}

class Employee implements Comparable<Employee>{
    //id是根据进入公司的先后顺序编码
    private int id;
    //姓名
    private String name;
    //职位
    private Position position;

    public Employee(int id, String name, Position position) {
        this.id = id;
        this.name = name;
        this.position = position;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", position=" + position +
                '}';
    }

    //按id号排序
    @Override
    public int compareTo(Employee o) {
//        return new CompareToBuilder().append(id,o.id).toComparison();
        return new CompareToBuilder()
                .append(position,o.position)
                .append(id,o.id).toComparison();
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Position getPosition() {
        return position;
    }
}

enum Position{
    Boss,Manager,Staff
}

class PositionComparator implements Comparator<Employee>{
    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getPosition().compareTo(o2.getPosition());
    }
}
